#!/bin/sh /etc/rc.common
# Copyright (C) 2008-2012 OpenWrt.org
START=90
USE_PROCD=1
CONFIG_DIR=/tmp/etc
CONFIG_FILE=$CONFIG_DIR/xpld.conf

add_mapping() {
	map="$map,$1"
}

add_map() {
	local	id

	config_get id $1 id
	map=""
	config_list_foreach $1 mapping add_mapping
	echo >>$CONFIG_FILE "map $id$map"
}

add_var() {
	vars="$vars,var=$1"	
}

add_code() {
	local	id

	config_get id $1 id
	vars=""
	code=""

	for name in type header zero one trail raw bits init repeat crc; do
		config_get value $1 $name
		[ ! -z "$value" ] && code=$code,$name=$value
	done

	config_list_foreach $1 var add_var
	echo >>$CONFIG_FILE "code $id$code$vars"
}

add_target() {
	[ -z "$target" ] && target=$1 || target=$target:$1
}

add_xpl_forward() {
	local	source
	local	target

	config_get source $1 source
	target=""
	config_list_foreach $1 target add_target
	echo >>$CONFIG_FILE "fwd $source=$target"
}

reload_service() {
	restart_service
}

service_triggers() {
	procd_add_reload_trigger "xpl"
}

start_service() {
	mkdir -p $CONFIG_DIR
	rm $CONFIG_FILE 2>/dev/null

	config_load xpl
	config_foreach add_map map 
	config_foreach add_code code
	config_foreach add_xpl_forward forward

	[ -e $CONFIG_FILE ] && {
		procd_open_instance
		procd_set_param command /usr/bin/xplmulti xpld -s -i $CONFIG_FILE
		procd_set_param respawn
		procd_close_instance
	}
}
